package com.mediacloud.app.newsmodule.view

import android.app.Activity
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Point
import android.graphics.drawable.Drawable
import android.text.TextUtils
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.fragment.app.FragmentActivity
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import com.mediacloud.app.assembly.util.*
import com.mediacloud.app.model.interfaces.IPermissionsAgree
import com.mediacloud.app.model.interfaces.PermissionUtil
import com.mediacloud.app.model.news.ArticleItem
import com.mediacloud.app.model.utils.ViewUtils
import com.mediacloud.app.newsmodule.R
import com.mediacloud.app.newsmodule.adaptor.comment.ShareCommentItem
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig
import com.mediacloud.app.reslib.enums.PosterShareBean
import com.mediacloud.app.share.SocialShareControl
import com.mediacloud.app.share.view.SharePopGridWindow
import com.utils.MatchWImage2
import io.reactivex.disposables.Disposable
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.uiThread
import java.io.File
import java.text.DecimalFormat

class PosterShareGridPop2(context: Context, val isMic: Boolean = false) : SharePopGridWindow(context) {
    var isPosterShareMode = false
    var shareViewParent: View? = null
    var shareView: PosterShareView? = null
    var logoIv: MatchWImage2? = null
    var summary: TextView? = null
    var titleTv: TextView? = null
    var newsPoster: View? = null
    var qrCodeIv: ImageView? = null
    var isNewsShare = false

    var micLivePostView: View? = null
    var ticketView: View? = null
    var disposable: Disposable? = null

    init {
        micLivePostView = contentView.findViewById(R.id.micLivePostView)
        ticketView = contentView.findViewById(R.id.ticketView)
        qrCodeIv = contentView.findViewById(R.id.qrCodeIv)
        newsPoster = contentView.findViewById(R.id.newsPoster)
        shareView = contentView.findViewById(R.id.shareView)
        titleTv = contentView.findViewById(R.id.titleTv)
        logoIv = contentView.findViewById(R.id.logoIv)
        summary = contentView.findViewById(R.id.summary)
        shareViewParent = contentView.findViewById(R.id.shareViewParent)
        val funcationGrid = contentView.findViewById<RecyclerView>(R.id.funcationGrid)
        funcationGrid.adapter = adaptor

    }

    override fun getResLayoutId(): Int {
        return R.layout.popwin_share_posterimage2
    }

    override fun show(view: Activity) {
        shareView?.removeAllViews()
        super.show(view)
    }

    override fun dismiss() {
        disposable?.dispose()
        shareView?.setOnClickListener(null)
        isPosterShareMode = false
        newsPoster?.visibility = View.GONE
        micLivePostView?.visibility = View.GONE
        super.dismiss()
    }

    /**
     * 新闻的
     */
    fun updateData(article: ArticleItem) {

        if (isMic) {
            micLivePostView?.visibility = View.VISIBLE
            val titleTv: TextView = findViewById(R.id.titleTv2)
            val startTimeTv: TextView = findViewById(R.id.startTimeTv)
            val hitCountTv: TextView = findViewById(R.id.hitCountTv)
            val qrCodeIv: ImageView = findViewById(R.id.qrCodeIv2)
            val logoIv: ImageView = findViewById(R.id.logoIv2)

            logoIv.loadSrc2(
                article.logo,
                context.resources.getDimensionPixelSize(R.dimen.dimen3),
                AppFactoryGlobalConfig.getDefaultImageLoadDrawable()
            )
            titleTv.text = article.title

            val qrCode = QRCodeUtil.createQRImage("${article.url}", qrCodeIv.width, qrCodeIv.height, null)
            qrCodeIv.setImageBitmap(qrCode)

            article.orginDataObject?.optJSONObject("AppCustomParams")
                ?.optJSONObject("movie")?.apply {
                    startTimeTv.text = optString("startTime_format")
                }
            if (article.hitCount == 0L) {
                hitCountTv.visibility = View.INVISIBLE
            } else {
                hitCountTv.visibility = View.VISIBLE
                val decimalFormat = DecimalFormat("00000000")
                val numFormat: String = decimalFormat.format(article.hitCount)
                hitCountTv.text = "NO.$numFormat"
            }
//            disposable = DataInvokeUtil.ziMeiTiApi.getAppointmentCount(6, "${article?.id}")
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe {
//                    if (it.optBoolean("state")) {
//                        it.optJSONObject("data")?.optInt("counts")?.let {
//
//                            val decimalFormat = DecimalFormat("00000000")
//                            val numFormat: String = decimalFormat.format(article.localAppointId)
//                            hitCountTv.text = "NO.$numFormat"
//                        }
//                    }
//                }


        } else {
            isNewsShare = true
            titleTv?.text = article.title
            titleTv?.paint?.isFakeBoldText = true
            if (TextUtils.isEmpty(article.logo)) {
                logoIv?.visibility = View.GONE
                summary?.visibility = View.VISIBLE
                summary?.text = article?.summary
            } else {
                summary?.visibility = View.GONE
                loadX(context, buildUrl(3, article.logo), 1, object : RequestListener<Drawable> {
                    override fun onLoadFailed(e: GlideException?, model: Any?, target: Target<Drawable>?, isFirstResource: Boolean): Boolean {
                        return true
                    }

                    override fun onResourceReady(resource: Drawable?, model: Any?, target: Target<Drawable>?, dataSource: DataSource?, isFirstResource: Boolean): Boolean {
                        logoIv?.setImageDrawable(resource)
                        logoIv?.visibility = View.VISIBLE
                        return true
                    }
                })
            }
            val qrCode = QRCodeUtil.createQRImage(article.url, qrCodeIv!!.width, qrCodeIv!!.height, null)
            qrCodeIv?.setImageBitmap(qrCode)
            newsPoster?.visibility = View.VISIBLE
        }
    }


    /**
     *  评论分享
     */
    fun updateData(posterShareBean: PosterShareBean, article: ShareCommentItem) {
        val titlePointTL = posterShareBean.title_coordinate_top_left.split(",")
        val titlePointBR = posterShareBean.title_coordinate_lower_right.split(",")
        val titlePoint = PointView(
            Point(titlePointTL[0].toInt(), titlePointTL[1].toInt()),
            Point(titlePointBR[0].toInt(), titlePointBR[1].toInt()),
            PointType.Title,
            article.title
        )

        val contentPointTL = posterShareBean.content_coordinate_top_left.split(",")
        val contentPointBR = posterShareBean.content_coordinate_lower_right.split(",")
        val contentPoint = PointView(
            Point(contentPointTL[0].toInt(), contentPointTL[1].toInt()),
            Point(contentPointBR[0].toInt(), contentPointBR[1].toInt()),
            PointType.CommentContent,
            article
        )

        val qrCodePointTL = posterShareBean.qr_coordinate_top_left.split(",")
        val qrCodePointBR = posterShareBean.qr_coordinate_lower_right.split(",")
        val qrCodePoint = PointView(
            Point(qrCodePointTL[0].toInt(), qrCodePointTL[1].toInt()),
            Point(qrCodePointBR[0].toInt(), qrCodePointBR[1].toInt()),
            PointType.QrCode,
            article.url
        )

        val pointList = mutableListOf(titlePoint, contentPoint, qrCodePoint)
        shareView!!.pointView = pointList
        shareView!!.removeAllViews()
        shareView!!.postDelayed({
            shareView!!.loadPosterImage(posterShareBean.back_img)
        }, 300)
    }

    /**
     * 邀请码
     */
//    fun updateInviteData(view: View) {
//        val scaleValue = 1.0F
//        shareView.removeAllViews()
//        val lp = RelativeLayout.LayoutParams(-1, -1)
//        val parentWidth = shareViewParent.measuredWidth - dp2px(context, 31)!!.toInt() * 2
//        val parentHeight = shareViewParent.measuredHeight - dp2px(context, 22)!!.toInt() * 2
//        lp.width = (parentWidth * scaleValue).toInt()
//        lp.height = (parentHeight * scaleValue).toInt()
//        shareView.addView(view, lp)
//    }

    fun saveImage() {
        PermissionUtil.invokeStoragePermission(
            contentView.context as FragmentActivity,
            object : IPermissionsAgree {
                override fun onAgree() {
                    save()
                }

                override fun onRefuse() {
                    dismiss()
                }

                override fun hasPermissions() {
                    save()
                }
            })

    }

    private fun save() {
        doAsync {
            val bitmap: Bitmap? = if (isMic) {
                BitmapUtil.convertViewToBitmap(ticketView)
            } else if (isNewsShare) {
                BitmapUtil.convertViewToBitmap(newsPoster)
            } else {
                BitmapUtil.convertViewToBitmap(shareView)
            }

            val path = FileUtil.getPhotoApp() + "/" + System.currentTimeMillis() + ".png"
            FileUtil.saveBitmap(path, bitmap)
            uiThread {
                val file = File(path)
                Utility.insertIntoMediaStore(contentView.context, false, file, file.lastModified())
                toastCenter(contentView.context, "图片保存成功")
                dismiss()
                bitmap?.recycle()
            }
        }
    }

    fun shareImage(share_media: Int) {
        PermissionUtil.invokeStoragePermission(contentView.context as FragmentActivity, object : IPermissionsAgree {
            override fun onAgree() {
                realShare(share_media)
            }

            override fun onRefuse() {
            }

            override fun hasPermissions() {
                realShare(share_media)
            }
        })
    }

    private fun realShare(share_media: Int) {
        doAsync {
            val bitmap: Bitmap? = if (isMic) {
                BitmapUtil.convertViewToBitmap(ticketView)
            } else if (isNewsShare) {
                BitmapUtil.convertViewToBitmap(newsPoster)
            } else {
                BitmapUtil.convertViewToBitmap(shareView)
            }
            val path = FileUtil.saveShareBitmap(bitmap)
            uiThread {
                SocialShareControl.share(ViewUtils.searchTintContextHostActivity(contentView.context), share_media, path)
                SocialShareControl.addSocialShareListener(object : SocialShareControl.SocialShareListener {

                    override fun shareComplete(p0: Int, p1: HashMap<String, Any>?) {
                        dismiss()
                        SocialShareControl.removeSocialShareListener(this)
                    }

                    override fun shareCancel(p0: Int) {
                        dismiss()
                        SocialShareControl.removeSocialShareListener(this)
                    }

                    override fun shareError(p0: Int, p1: String?) {
                        dismiss()
                        SocialShareControl.removeSocialShareListener(this)
                    }
                })
            }
        }
    }
}